package address;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.*;

public class SearchAddr {

	static String checknum = "";
	static int i;
	static String num;

	static String dlastName;
	static String dfirstName;
	static String dposition;
	static String ddivision;
	static String dcompany;
	static String daddress;
	static String dphoneNumber;
	static String dfaxNumber;
	static String dmobileNumber;
	static String demail;
	static String dhomepage;
	
	public int getCount(){
		return i;
	}
	
	public String getNumber(){
		return num;
	}
	
	public String getLastName(){
		return dlastName;
	}
	
	public String getFirstName(){
		return dfirstName;
	}
	
	public String getAddress(){
		return daddress;
	}
	
	
	public String getMobileNum(){
		return dmobileNumber;
	}
	
	public static int search() {

		Scanner scanner = new Scanner(System.in);

		String lastName;
		String firstName;
		String mobileNumber;

		String no;

		boolean check = true;

		while (check) {
			System.out.print("성 또는 이름을 검색해주세요:");
			String input = scanner.nextLine();
			no = search_query(input);
			if (!no.equals("-1"))
				menu(no);

			check = false;
			return 0;

		}

		scanner.close();

		return 0;
	}

	static String search_query(String input) {

		Connection conn = null;
		String result="-1";
		try {
			Class.forName("com.mysql.jdbc.Driver");
			conn = DriverManager.getConnection(
							"jdbc:mysql://localhost:3306/jmk?useUnicode=true&characterEncoding=utf-8",
							"root", "websys");

			Statement stmt = conn.createStatement();

			ResultSet rs = stmt.executeQuery("SELECT no,lastName,firstName, mobileNumber FROM address where firstName like '%"
							+ input + "%' or lastName like '%" + input + "%'");
			i=0;
			String no;
			String lastName;
			String firstName;
			String mobileNumber;
			if (rs.next()) {
				do {

					no = rs.getString("no");
					num = no;
					checknum += String.valueOf(no);
					checknum += String.valueOf(",");

					System.out.println("-----연락처" + no + "-----");
					lastName = rs.getString("lastName");
					firstName = rs.getString("firstName");
					mobileNumber = rs.getString("mobileNumber");

					System.out.println("성:" + lastName + "");
					System.out.println("이름:" + firstName + "");
					System.out.println("핸드폰번호:" + mobileNumber + "");
					result = no;
					i++;

				} while (rs.next());

			} else {
				result = "-1";
				System.out.println("검색결과가 없습니다.");

			}
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return result;

	}
	
	public static int menu(String no) {

		boolean menucheck = true;
		Scanner scanner = new Scanner(System.in);
		String ans = "";
		menucheck = true;
		
		String[] checkno;
		checkno = new String[100];
		
		for (int i = 0; i < 100; i++) {
			checkno[i] = "0";
		}

		String choice;
		boolean check = true;
		
		while (check) {
			
			System.out.print("편집할 연락처의 고유번호를 입력해주세요.:");
			String input = scanner.nextLine();

			checkno = checknum.split(",");
			for (int i = 0; i < checkno.length; i++) {
				if (checkno[i].equals(input)) {
					no = input;
					while (menucheck) {
						menucheck = false;
						try {

							System.out.println("1. 연락처 수정");
							System.out.println("2. 연락처 삭제");
							System.out.println("3. 연락처 상세보기");
							System.out.println("4. 메인화면 돌아가기");

							System.out.println("항목을 선택해주세요: ");
							ans = scanner.next();

						} catch (InputMismatchException e) {
							System.out.println("1~4사이의 값을 입력하세요.");
							menucheck = true;
						}

						switch (ans) {
						case "1": {
							modify(no);
							menucheck = true;
							return 0;
						}
						case "2": {
							delete(no);
							menucheck = true;
							return 0;
						}
						case "3": {
							detailInfo(no);
							menucheck = true;
							return 0;
						}
						case "4": {

							return 0;
						}

						default: {
							System.out.println("1~4 내의 항목을 선택해주세요!");
							menucheck = true;
							break;
						}
						}

					}

				}
			}
		}
		System.out.println("입력이 틀렸습니다.");

		return 0;

	}

	public static int modify(String no) {

		Scanner input = new Scanner(System.in);
		int n_no = Integer.parseInt(no);
		String[] checkno;
		checkno = new String[100];
		
		for (int i = 0; i < 100; i++) {
			checkno[i] = "0";
		}

		Connection conn = null;
		String lastname = "";
		String firstname = "";
		String position = "";
		String division = "";
		String company = "";
		String addr = "";
		String phNum = "";
		String faxNum = "";
		String mobileNum = "";
		String email = "";
		String homepage = "";

		try {
			Class.forName("com.mysql.jdbc.Driver");
			conn = DriverManager.getConnection(
							"jdbc:mysql://localhost:3306/jmk?useUnicode=true&characterEncoding=utf-8",
							"root", "websys");
			Statement stmt = conn.createStatement();

			boolean editcontinue = true;

			while (editcontinue) {
				ResultSet rs = stmt.executeQuery("SELECT * FROM address where no = " + no);

				if (rs.next()) {

					lastname = rs.getString("lastName");
					firstname = rs.getString("firstName");
					position = rs.getString("position");
					division = rs.getString("division");
					company = rs.getString("company");
					addr = rs.getString("address");
					phNum = rs.getString("phoneNumber");
					faxNum = rs.getString("faxNumber");
					mobileNum = rs.getString("mobileNumber");
					email = rs.getString("email");
					homepage = rs.getString("homepage");

					System.out.println("1. 성: " + lastname);
					System.out.println("2. 이름 " + firstname);
					System.out.println("3. 직책  " + position);
					System.out.println("4. 부서  " + division);
					System.out.println("5. 회사  " + company);
					System.out.println("6. 주소 " + addr);
					System.out.println("7. 전화 번호 " + phNum);
					System.out.println("8. 팩스 번호 " + faxNum);
					System.out.println("9. 휴대폰 번호 " + mobileNum);
					System.out.println("10. e-mail " + email);
					System.out.println("11. 홈페이지 주소 " + homepage);
					System.out.println("이 항목에 대해서 수정합니다.");
					System.out.println("수정할 항목을 입력하세요.");

					String menu = input.next();

					switch (menu) {

					case "0":
					case "1":
						System.out.println("이름을 입력하세요.");
						firstname = input.next();
						break;
					case "2":
						System.out.println("성을 입력하세요.");
						lastname = input.next();
						break;
					case "3":
						System.out.println("직책을 입력하세요.");
						position = input.next();
						break;
					case "4":
						System.out.println("부서를 입력하세요.");
						division = input.next();
						break;
					case "5":
						System.out.println("회사를 입력하세요.");
						company = input.next();
						break;
					case "6":
						System.out.println("주소를 입력하세요.");
						addr = input.next();
						break;
					case "7":
						System.out.println("전화번호를 입력하세요.(숫자만)");
						phNum = input.next();
						break;
					case "8":
						System.out.println("팩스번호를 입력하세요.(숫자만)");
						faxNum = input.next();
						break;
					case "9":
						System.out.println("휴대폰번호를 입력하세요.(숫자만)");
						mobileNum = input.next();
						break;
					case "10":
						System.out.println("이메일을 입력하세요.");
						email = input.next();
						break;
					case "11":
						System.out.println("홈페이지 주소를 입력하세요.");
						homepage = input.next();
						break;
					default:
						System.out.println("0~11까지의 숫자를 입력하세요.");
						break;

					}
					
					modify_query(lastname,firstname,position,division,company,addr,phNum,faxNum,mobileNum,email,homepage,n_no);

				}
				
				System.out.println("계속해서 수정하시겠습니까? 예(y | Y) 메인으로 돌아가기(아무 문자나 입력)");
				
				String ans = input.next();
				
				if (ans.equals("y") || ans.equals("Y"))
					editcontinue = true;
				else {
					System.out.println("전화번호부 수정을 마칩니다.");
					editcontinue = false;
					return 0;
				}

			}

		} catch (SQLException | ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return 0;

	}

	static void modify_query(String lastname, String firstname,
			String position, String division, String company, String addr,
			String phNum, String faxNum, String mobileNum, String email,
			String homepage, int n_no) {
		
		Connection conn = null;
		try {
			Class.forName("com.mysql.jdbc.Driver");
			conn = DriverManager.getConnection(
							"jdbc:mysql://localhost:3306/jmk?useUnicode=true&characterEncoding=utf-8",
							"root", "websys");
			Statement stmt = conn.createStatement();
		
		String query = "UPDATE address SET lastName='" + lastname
				+ "', firstName='" + firstname + "', position='"
				+ position + "', division='" + division
				+ "', company='" + company + "', address='" + addr
				+ "', phoneNumber='" + phNum + "', faxNumber = '"
				+ faxNum + "', mobileNumber='" + mobileNum
				+ "', email='" + email + "', homepage='" + homepage
				+ "'" + " where no=" + n_no;
		stmt.execute(query);
		
		} catch (SQLException | ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		// TODO Auto-generated method stub
		
	}

	public static int delete(String no) {

			Scanner scanner = new Scanner(System.in);

			String choice;

			boolean check = true;
			while (check) {

				System.out.print("비밀번호를 입력하세요 : ");
				String pw = scanner.next();
				
				if (PwEdit.pw_check(pw)) {
					
					System.out.print("정말로 삭제하시겠습니까?(Y/N)");
					choice = scanner.next();

					if (choice.equals("Y") || choice.equals("y")) {
						delete_query(no);
						System.out.println("해당 번호 삭제 완료!");
						check = false;
					} else if (choice.equals("N") || choice.equals("n")) {
						check = false;
						return 0;
					}
				} else {
					System.out.print("비밀번호가 불일치 합니다.");
					check = true;
				}

			}

			return 0;
		
	}

	static void delete_query(String no) {
		
		Connection conn = null;
		try {
			Class.forName("com.mysql.jdbc.Driver");
			conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/jmk?useUnicode=true&characterEncoding=utf-8","root", "websys");
			Statement stmt = conn.createStatement();
		
			String query = "DELETE from address where no='" + no + "'";
			stmt.execute(query);
			
			}catch (ClassNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		// TODO Auto-generated method stub
		
	}

	public static int detailInfo(String no) {
		Connection conn = null;

		try {
			Class.forName("com.mysql.jdbc.Driver");
			conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/jmk?useUnicode=true&characterEncoding=utf-8","root", "websys");

			Statement stmt = conn.createStatement();
			Scanner scanner = new Scanner(System.in);

			String lastName;
			String firstName;
			String position;
			String division;
			String company;
			String address;
			String phoneNumber;
			String faxNumber;
			String mobileNumber;
			String email;
			String homepage;

			ResultSet rs = stmt.executeQuery("SELECT lastName,firstName,position,division,company,address,phoneNumber,faxNumber, mobileNumber,email,homepage FROM address where no='"
							+ no + "'");

			while (rs.next()) {
				lastName = rs.getString("lastName");
				firstName = rs.getString("firstName");
				position = rs.getString("position");
				division = rs.getString("division");
				company = rs.getString("company");
				address = rs.getString("address");
				phoneNumber = rs.getString("phoneNumber");
				faxNumber = rs.getString("faxNumber");
				mobileNumber = rs.getString("mobileNumber");
				email = rs.getString("email");
				homepage = rs.getString("homepage");

				System.out.println("-----------------");
				System.out.println("성:" + lastName + "");
				System.out.println("이름:" + firstName + "");
				System.out.println("직위:" + position + "");
				System.out.println("부서:" + division + "");
				System.out.println("회사명:" + company + "");
				System.out.println("주소:" + address + "");
				System.out.println("전화번호:" + phoneNumber + "");
				System.out.println("팩스번호:" + faxNumber + "");
				System.out.println("핸드폰번호:" + mobileNumber + "");
				System.out.println("이메일주소:" + email + "");
				System.out.println("홈페이지주소:" + homepage + "");
				System.out.println("-----------------");

			}
			System.out.println("메뉴로 돌아가기(아무키나 누르시오)");
			String ans = scanner.next();

			if (ans != null) {
				return 0;
			}

		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return 0;

	}
	
	static void detailInfo_query(String no) {
		Connection conn = null;

		try {
			Class.forName("com.mysql.jdbc.Driver");
			conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/jmk?useUnicode=true&characterEncoding=utf-8","root", "websys");

			Statement stmt = conn.createStatement();
			

			ResultSet rs = stmt.executeQuery("SELECT lastName,firstName,position,division,company,address,phoneNumber,faxNumber, mobileNumber,email,homepage FROM address where no='"
							+ no + "'");

			while (rs.next()) {
				dlastName = rs.getString("lastName");
				dfirstName = rs.getString("firstName");
				dposition = rs.getString("position");
				ddivision = rs.getString("division");
				dcompany = rs.getString("company");
				daddress = rs.getString("address");
				dphoneNumber = rs.getString("phoneNumber");
				dfaxNumber = rs.getString("faxNumber");
				dmobileNumber = rs.getString("mobileNumber");
				demail = rs.getString("email");
				dhomepage = rs.getString("homepage");

				System.out.println("-----------------");
				System.out.println("성:" + dlastName + "");
				System.out.println("이름:" + dfirstName + "");
				System.out.println("직위:" + dposition + "");
				System.out.println("부서:" + ddivision + "");
				System.out.println("회사명:" + dcompany + "");
				System.out.println("주소:" + daddress + "");
				System.out.println("전화번호:" + dphoneNumber + "");
				System.out.println("팩스번호:" + dfaxNumber + "");
				System.out.println("핸드폰번호:" + dmobileNumber + "");
				System.out.println("이메일주소:" + demail + "");
				System.out.println("홈페이지주소:" + dhomepage + "");
				System.out.println("-----------------");

			} 
		}catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}
